<template>
  <div>
    <el-dialog
      :title="isEdit ? '修改' : title"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <el-form ref="form" :model="form" label-width="100px">
        <el-form-item label="主题">
          <el-input v-model="form.theme" clearable></el-input>
        </el-form-item>
        <el-form-item label="内容">
          <!-- <div style="border: 1px solid #ccc;" class="editor">
                    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig" :mode="mode" />
                    <Editor style="height: 400px; overflow-y: hidden;" v-model="form.content" @input="handleInput"
                        :defaultConfig="editorConfig" :mode="mode" @onCreated="onCreated" @onChange="onChange"
                        @onMaxLength="onMaxLength" />
                </div> -->
          <div
            v-for="(item, index) in dataList"
            style="display: flex; flex-direction: row; margin-bottom: 5px"
            :key="index"
          >
            <el-input
              v-model="item.title"
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
            ></el-input>
            <div style="display: flex; flex-direction: row; width: 140px">
              <el-button
                type="text"
                icon="el-icon-circle-plus-outline"
                style="margin-left: 10px"
                @click="addHandle"
                v-if="index == 0"
                >添加</el-button
              >
              <el-button
                type="text"
                icon="el-icon-remove"
                style="margin-left: 10px; color: red"
                @click="deleteHandle(index)"
                v-else
                >删除</el-button
              >
            </div>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitHandle">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import workGuide from '@/api/workGuide/index'
import { getToken } from '@/utils/auth'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { DomEditor } from '@wangeditor/editor'
import '@wangeditor/editor/dist/css/style.css'
import { Loading } from 'element-ui'
export default {
  name: 'HandbookDialog',
  components: {
    Editor,
    Toolbar,
  },
  props: {
    title: {
      type: String,
      default: '新增',
    },
  },
  data() {
    return {
      dialogVisible: false,
      isEdit: false, //是否编辑
      form: {
        id: '',
        clubType: '0', //俱乐部类型
        theme: '',
        content: '', //描述
      },
      dataList: [
        {
          title: '',
        },
      ],
      editor: null,
      mode: 'default', // or 'simple'
      toolbarConfig: {
        // 排除工具栏配置
        excludeKeys: [
          // 全屏，网络视频，本地视频，表情，代码，待办，代码块，插入图片
          'fullScreen',
          'uploadVideo',
          'group-video',
          'emotion',
          'code',
          'todo',
          'codeBlock',
          'insertImage',
        ],
        insertKeys: {
          keys: ['ParagraphSpacingBefore', 'ParagraphSpacingAfter'],
          index: 10,
        },
      },
      editorConfig: {
        placeholder: '请输入内容...',
        maxLength: this.maxLength, // 限制富文本输入文本字数
        MENU_CONF: {
          uploadImage: {
            // 最多可上传几个文件，默认为 100
            // maxNumberOfFiles: 10,
            // 单个文件的最大体积限制，默认为 2M
            maxFileSize: 1 * 1024 * 1024 * 50, // 1M
            // 小于该值就插入 base64 格式（而不上传），默认为 0
            base64LimitSize: 5 * 1024, // 5kb
            // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制
            allowedFileTypes: ['image/*'],
            // 图片上传
            async customUpload(file, insertFn) {
              const formData = new FormData()
              formData.append('file', file)
              let loading = Loading.service({
                fullscreen: true,
                lock: true,
                text: '正在加载，请耐心等待...',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)',
              })
              workGuide
                .upFile(formData)
                .then((res) => {
                  loading.close()
                  insertFn(res.url, 'image')
                })
                .catch(() => {
                  loading.close()
                })

              // const res = await uploadF(formData)
              // if (res.data) {
              //     insertFn(`图片地址`, 'image')
              // } else {
              //     this.$message.error('图片上传失败，请重新上传!');
              // }
            },
          },
          fontFamily: {
            fontFamilyList: [
              { name: '仿宋', value: 'fangsong' },
              { name: '黑体', value: 'Arial' },
              { name: '宋体', value: 'SimSun' },
              { name: '楷书', value: 'KaiTi' },
              { name: '隶书', value: 'LiSu' },
            ],
          },
        },
      },
    }
  },
  computed: {
    uploadUrl() {
      return process.env.VUE_APP_BASE_API + '/public/file/upload'
    },
    headers() {
      return { Authorization: getToken() }
    },
  },

  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
      this.$nextTick(() => {
        const toolbar = DomEditor.getToolbar(this.editor)
        this.curToolbarConfig = toolbar.getConfig()
      })
    },
    handleInput(value) {
      this.$emit('change', value) // 将内容同步到父组件中
    },
    onChange(editor) {
      // 监听富文本输入
      const text = editor.getText().replace(/\n|\r/gm, '')
      this.textLength = text.length
    },
    onMaxLength(editor) {
      // 当输入值达到限制值时触发事件
      this.$message.warning('输入文本数已到达最大值！')
    },
    submitHandle() {
      if (this.dataList.length == 1 && this.dataList[0]['title'].length == 0) {
        this.$message.warning('内容不能为空')
        return
      }
      this.form.content = JSON.stringify(this.dataList)
      if (this.isEdit) {
        //修改
        workGuide
          .editHandle(this.form)
          .then((res) => {
            this.dialogVisible = false
            this.$notify({ message: '操作成功', type: 'success' })
            this.$emit('submitSuccess')
          })
          .catch(() => {})
      } else {
        workGuide
          .addHandle(this.form)
          .then((res) => {
            this.dialogVisible = false
            this.$notify({ message: '操作成功', type: 'success' })
            this.$emit('submitSuccess')
          })
          .catch(() => {})
      }
    },
    addHandle() {
      this.dataList.push({
        title: '',
      })
    },
    deleteHandle(index) {
      this.dataList.splice(index, 1)
    },
  },
}
</script>

<style lang="scss"></style>
